package com.jml.netty.手写dubbo.server.consumer;



import com.jml.netty.手写dubbo.server.register.MarshallingCodeCFactory;
import com.jml.netty.手写dubbo.server.req.RpcRequest;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.InetSocketAddress;
import java.net.URLDecoder;
import java.util.List;
import java.util.concurrent.CountDownLatch;


public class RpcClientProxy {

    private ServiceDiscover serviceDiscover = new ServiceDiscover();

    public <T> T create(Class<T> tClass) {
        //生成一个代理类
        return (T) Proxy.newProxyInstance(tClass.getClassLoader(), new Class[]{tClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                String serviceName = tClass.getName();
                // 1. 根据服务名称 去zk上获取接口调用地址 jmlrpc://127.0.0.1:8093
                List<String> discover = serviceDiscover.getDiscover(serviceName);
                //jmlrpc://127.0.0.1:8093
                String addres = discover.get(0);
                RpcRequest rpcRequest = new RpcRequest(serviceName, method.getName(), method.getParameterTypes(), args);
                // 2.拼接调用接口地址jmlrpc://127.0.0.1:8093/com.jml.netty.手写dubbo.api.MemberService getgetUser(1)  tClass.getName
                // 3.使用nettyclient向netty服务器端发送消息  jmlrpc  //127.0.0.1   8093
                String[] splitAddres = URLDecoder.decode(addres, "UTF-8").split(":");
                String host = splitAddres[1].replace("//","");
                String port = splitAddres[2];
                return sendMsg(host, Integer.parseInt(port), rpcRequest);
            }
        });
    }

    public Object sendMsg(String host, int port, RpcRequest rpcRequest) {
        DubboClientHandler dubboClientHandler = new DubboClientHandler();
        //创建nioEventLoopGroup
        NioEventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group).channel(NioSocketChannel.class)
                .remoteAddress(new InetSocketAddress(host, port))
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingDecoder());
                        ch.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingEncoder());
                        ch.pipeline().addLast(dubboClientHandler);
                    }
                });
        try {
            // 发起同步连接
            ChannelFuture sync = bootstrap.connect().sync();
            //netty的调用时异步，可能还没返回数据主线程就结束了，这里需要阻塞等待结果返回。
            sync.channel().writeAndFlush(rpcRequest);
            countDownLatch.await();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
        //得到返回参数
        return dubboClientHandler.getResponse();

    }

    private CountDownLatch countDownLatch = new CountDownLatch(1);

    public class DubboClientHandler extends ChannelInboundHandlerAdapter {
        private Object response;

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            System.out.println("消费者获取到消息:" + msg);
            this.response = msg;
            countDownLatch.countDown();
        }


        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            cause.printStackTrace();
            ctx.close();
        }

        public Object getResponse() {
            return this.response;
        }
    }
}
